﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using HCFramework.API.LINQ;
using System.IO;

namespace C
{
    public class ManufacturerController
    {
        public static List<Manufacturer> ListManufacturerCache = GetAll();

        private static List<Manufacturer> GetAll()
        {
            HCDataContext db = new HCDataContext();
            return db.Manufacturers.ToList();
        }

        public static void Insert(Manufacturer a)
        {
            HCDataContext db = new HCDataContext();
            db.Manufacturers.InsertOnSubmit(a);
            db.SubmitChanges();

            ListManufacturerCache = GetAll();
        }

        public static void Update(Manufacturer a, HCDataContext db)
        {
            // Nếu thay đổi ảnh thì xóa ảnh cũ
            Manufacturer oldRecord = GetByID(a.ManufacturerID);
            if (oldRecord.LogoUrl != a.LogoUrl)
            {
                if (oldRecord.LogoUrl.StartsWith("/"))
                {
                    string filePath = HttpContext.Current.Server.MapPath("~" + oldRecord.LogoUrl);
                    if (File.Exists(filePath)) File.Delete(filePath);
                }
            }

            db.SubmitChanges();

            ListManufacturerCache = GetAll();
        }

        public static void Delete(int id)
        {
            HCDataContext db = new HCDataContext();
            Manufacturer a = db.Manufacturers.Where(
                ik => ik.ManufacturerID == id).First();

            // Xoa file vat ly neu co
            if (a.LogoUrl.StartsWith("/"))
            {
                string filePath = HttpContext.Current.Server.MapPath("~" + a.LogoUrl);
                if (File.Exists(filePath)) File.Delete(filePath);
            }

            db.Manufacturers.DeleteOnSubmit(a);
            db.SubmitChanges();

            ListManufacturerCache = GetAll();
        }

        public static Manufacturer GetByID(int id, HCDataContext db)
        {
            return db.Manufacturers.Where(
                ik => ik.ManufacturerID == id).FirstOrDefault();
        }

        public static Manufacturer GetByID(int id)
        {
            return GetByID(id, new HCDataContext());
        }
    }
}